package ar.uba.dc.cmovil.tripplanner.services;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import ar.uba.dc.cmovil.tripplanner.domain.Coordinate;
import ar.uba.dc.cmovil.tripplanner.domain.Location;

/**
 * Created by anton on 10/27/13.
 */
public class GetCoordinatesByNameTask extends AsyncTask<String, Void, Location> {

    private final Context context;
    private HttpTaskHandler<Location> handler;
    private Location result;

    public GetCoordinatesByNameTask(Context context, HttpTaskHandler<Location> handler) {
        super();

        this.context = context;
        this.handler = handler;
    }

    @Override
    protected Location doInBackground(String... strings) {
        String name = strings[0];
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocationName(name, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (addresses == null || addresses.size() == 0) {
            result = null;
        } else {
            Address address = addresses.get(0);
            result = new Location(new Coordinate(address.getLatitude()), new Coordinate(address.getLongitude()));
        }
        return result;
    }

    @Override
    protected void onPostExecute(Location location) {
        super.onPostExecute(location);
        handler.onSuccess(result);
    }
}
